package com.cmy.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author : Cmy
 * @date : 2025-03-19 14:42
 */
@Slf4j
public class DDLResourceLoader {

    /**
     * 加载资源文件
     * key filename
     * value Resource 对象
     * 非同名文件都会被执行
     * 同名文件按照以下顺序加载 后面的会覆盖前面的
     * classpath*:db/migration
     * file./db/migration
     * file:./resources/db/migration
     *
     * @return {@link Map }<{@link String }, {@link Resource }>
     */
    public static Map<String, Resource> loadFilenameResourceMap(){
        try {
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Map<String, Resource> nameResourceMap = new LinkedHashMap<>();
            Resource[] resources = resolver.getResources("classpath*:db/migration/**.*");//内部资源
            for (Resource resource : resources) {
                nameResourceMap.put(resource.getFilename(), resource);
            }
            Resource[] externalSiblingResources = resolver.getResources("file:./db/migration/**.*");//外部jar同级资源
            for (Resource externalSiblingResource : externalSiblingResources) {
                nameResourceMap.put(externalSiblingResource.getFilename(), externalSiblingResource);
            }
            Resource[] externalResources = resolver.getResources("file:./resources/db/migration/**.*");//外部resources下资源
            for (Resource externalResource : externalResources) {
                nameResourceMap.put(externalResource.getFilename(), externalResource);
            }
            return nameResourceMap;
        } catch (IOException e) {
            log.error(ThrowableUtil.getStackTrace(e));
        }
        return Collections.emptyMap();
    }

}

    